package com.hwxm.ltim.controller;

import com.hwxm.ltim.common.Result;
import com.hwxm.ltim.dto.LoginRequest;
import com.hwxm.ltim.dto.LoginResponse;
import com.hwxm.ltim.dto.RegisterRequest;
import com.hwxm.ltim.dto.ChangePasswordRequest;
import com.hwxm.ltim.dto.BindEmailRequest;
import com.hwxm.ltim.entity.User;
import com.hwxm.ltim.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody RegisterRequest request) {
        try {
            User user = userService.register(request);
            return Result.success("注册成功", user);
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {
        try {
            LoginResponse response = userService.login(request);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public Result<User> getUserInfo(@PathVariable Long userId, HttpServletRequest request) {
        try {
            // 验证用户只能查看自己的信息
            Long currentUserId = getCurrentUserId(request);
            if (!currentUserId.equals(userId)) {
                return Result.error("无权限查看其他用户信息");
            }
            
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/{userId}")
    public Result<User> updateUser(@PathVariable Long userId, @RequestBody User user, HttpServletRequest request) {
        try {
            // 验证用户只能修改自己的信息
            Long currentUserId = getCurrentUserId(request);
            if (!currentUserId.equals(userId)) {
                return Result.error("无权限修改其他用户信息");
            }
            
            // 以路径中的 userId 为准，避免被篡改
            user.setId(userId);
            User updated = userService.updateUser(user);
            return Result.success("更新成功", updated);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/{userId}/password")
    public Result<Boolean> changePassword(@PathVariable Long userId, @RequestBody ChangePasswordRequest req, HttpServletRequest request) {
        try {
            // 验证用户只能修改自己的密码
            Long currentUserId = getCurrentUserId(request);
            if (!currentUserId.equals(userId)) {
                return Result.error("无权限修改其他用户密码");
            }
            
            userService.changePassword(userId, req.getOldPassword(), req.getNewPassword());
            return Result.success("修改成功", true);
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public Result<User> searchUser(@RequestParam String keyword) {
        try {
            User user = userService.searchUser(keyword);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 绑定邮箱
     */
    @PostMapping("/bind-email")
    public Result<String> bindEmail(@RequestBody BindEmailRequest request, HttpServletRequest httpRequest) {
        try {
            // 从JWT token中获取用户ID
            Long userId = getCurrentUserId(httpRequest);
            userService.bindEmail(userId, request);
            return Result.success("邮箱绑定成功");
        } catch (Exception e) {
            log.error("绑定邮箱失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     * 从JWT拦截器中设置的请求属性中获取
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        }
        throw new RuntimeException("无法获取当前用户ID");
    }
}

